﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using UberChess.Structure.Move;

namespace UberChess.Structure.Pieces
{
    [Serializable]
   public class Bishop : IPiece
   {
       private const int MATERIAL_VALUE = 300;
       public Side side;
       private Vector2 _currentPosition;

       public Bishop(Side side, Vector2 currentPosition)
       {
           this.side = side;
           this._currentPosition = currentPosition;
       }

        public Vector2 CurrentPosition
        {
            get { return _currentPosition; }
            set { _currentPosition = value; }
        }

        public Rectangle GetSourceRectangle()
       {
           return new Rectangle((side == Side.WHITE ? 0 : Constants.PIECEWIDTH), Constants.PIECEHEIGHT * 3, Constants.PIECEWIDTH, Constants.PIECEHEIGHT);
       }

       public List<PossibleMove> GetPossibleMoves(State state)
       {
           var moves = new List<PossibleMove>();
           var m = new[] { new Vector2(1, 1), new Vector2(-1, 1), new Vector2(-1, -1), new Vector2(1, -1) };

           foreach (var vector2 in m)
           {
               var i = 1;
               while (true)
               {
                   var pos = _currentPosition + vector2 * i;
                   if (state.IsWithinBounds(pos))
                   {
                       var destination = state.GetPieceAtPosition(pos);
                       if ((destination.GetType() != typeof(Empty) && destination.GetSide() == this.side))
                           break;

                       if (destination.GetType() == typeof(Empty))
                           moves.Add(new PossibleMove(_currentPosition, pos, false));
                       else
                       {
                           moves.Add(new PossibleMove(_currentPosition, pos, true));
                           break;
                       }
                       i++;
                   }
                   else
                   {
                       break;
                   }
               }
           }
           return moves;
       }

       public List<PossibleMove> GetPossibleCaptureMoves(State state)
       {
           var possibleMoves = GetPossibleMoves(state);
           return possibleMoves.Where(move => move.isCaptureMove).ToList();
       }

       public Side GetSide()
       {
           return side;
       }

       public void SetCurrentPosition(Vector2 position)
       {
           _currentPosition = position;
       }

       public Vector2 GetCurrentPosition()
       {
           return _currentPosition;
       }

       public int GetMaterialValue()
      {
         return MATERIAL_VALUE;
      }
   }
}
